package com.alinesno.cloud.operation.cmdb.service.impl;

import javax.transaction.Transactional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.alinesno.cloud.operation.cmdb.entity.DeployEntity;
import com.alinesno.cloud.operation.cmdb.entity.MachineEntity;
import com.alinesno.cloud.operation.cmdb.entity.OrderHistoryEntity;
import com.alinesno.cloud.operation.cmdb.entity.OrderInfoEntity;
import com.alinesno.cloud.operation.cmdb.entity.OrdersEntity;
import com.alinesno.cloud.operation.cmdb.repository.DeployRepository;
import com.alinesno.cloud.operation.cmdb.repository.MachineRepository;
import com.alinesno.cloud.operation.cmdb.repository.OrderHistoryRepository;
import com.alinesno.cloud.operation.cmdb.repository.OrderInfoRepository;
import com.alinesno.cloud.operation.cmdb.repository.OrderRepository;
import com.alinesno.cloud.operation.cmdb.service.OrderService;

/**
 * 订单服务
 * 
 * @author WeiXiaoJin
 * @since 2018年10月12日 上午6:22:41
 */
@Service
public class OrderServiceImpl implements OrderService {

	@SuppressWarnings("unused")
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private OrderRepository orderRepository; // 订单服务

	@Autowired
	private DeployRepository deployRepository; // 订单服务

	@Autowired
	private OrderInfoRepository orderInfoRepository; // 订单服务

	@Autowired
	private MachineRepository machineRepository; // 虚拟机服务

	@Autowired
	private OrderHistoryRepository orderHistoryRepository; // 订单历史服务

	@Transactional
	@Override
	public void deleteOrder(String orderId) {
		OrdersEntity order = orderRepository.findByOrderId(orderId);
		OrderHistoryEntity orderHistory = new OrderHistoryEntity();

		BeanUtils.copyProperties(order, orderHistory);

		orderRepository.delete(order);
		orderHistoryRepository.save(orderHistory);
	}

	@Transactional
	@Override
	public boolean applyPass(String orderInfoId, String machineIds) {

		// 查询申请
		OrderInfoEntity orderInfo = orderInfoRepository.findById(orderInfoId).get();

		// 插入部署表中
		String[] machineIdArr = machineIds.split("\\|");
		
		for (String id : machineIdArr) {
			logger.debug("machine id:{}" , id);
			
			 MachineEntity machineEntity = machineRepository.findById(id).get() ; 
			 Assert.notNull(machineEntity , "虚拟机["+machineEntity.getMachineIp()+"]不存在");
			
			 DeployEntity deploy = new DeployEntity() ;
			 BeanUtils.copyProperties(orderInfo, deploy);
			 deploy.setMachineId(machineEntity.getId());
			 deploy.setMachineIp(machineEntity.getMachineIp());
			 deploy.setMachineId(machineEntity.getId());
			
			 deployRepository.save(deploy) ;
		}
		
		// 删除申请数据
		orderInfoRepository.delete(orderInfo);

		return true;
	}

}
